package com.blog.handler;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.blog.common.thread.BaseThread;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Random;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Random random = new Random();
        int meId = random.nextInt(32); // 机械id
        int daId = random.nextInt(32); // 数据中心id
        if (meId == daId) {
            daId = daId + 1;
        }
        Snowflake snowflake = new Snowflake(meId, daId);
        // 生成 ID
        long id = snowflake.nextId();

        log.info("开始插入自动填充");
        String userId = BaseThread.getId();
        this.strictInsertFill(metaObject, "id", String.class, id + "");
        this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class); // 起始版本 3.3.3(推荐)
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class); // 起始版本 3.3.3(推荐)
        this.strictInsertFill(metaObject, "createBy", String.class, userId);
        this.strictInsertFill(metaObject, "updateBy", String.class, userId);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始修改自动填充");
        String userId = BaseThread.getId();
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐)
        this.strictUpdateFill(metaObject, "updateBy", String.class, userId);
    }
}